//
//  HoverView.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/3/19.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class HoverView: NSView {
    
    var originalColor:NSColor? = NSColor.clear
    var highColor:NSColor = color_main108
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    convenience init(frame frameRect: NSRect,highColor:NSColor) {
        self.init(frame: frameRect)
        self.highColor = highColor
    }
    
    override func updateTrackingAreas() {
        self.setupHover()
        super.updateTrackingAreas()
    }
    
    func setupHover() {
        self.wantsLayer = true
        self.layer?.backgroundColor = NSColor.clear.cgColor
        
        let trackingArea = NSTrackingArea.init(rect: self.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited,NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil)
        self.addTrackingArea(trackingArea)
        if self.superview?.layer?.backgroundColor != nil {
            self.originalColor = NSColor.init(cgColor: self.layer!.backgroundColor!)
        }
    }
    
    override func mouseEntered(with event: NSEvent) {
        self.superview?.layer?.backgroundColor = self.highColor.cgColor
        super.mouseEntered(with: event)
    }
    
    override func mouseExited(with event: NSEvent) {
        self.superview?.layer?.backgroundColor = self.originalColor?.cgColor
        super.mouseExited(with: event)
    }
}

extension NSView {
    func setHover(color:NSColor=color_main108)  {
        let view = HoverView.init(frame: self.bounds,highColor: color)
        view.autoresizingMask = [NSView.AutoresizingMask.width,NSView.AutoresizingMask.height]
        self.addSubview(view, positioned: NSWindow.OrderingMode.below, relativeTo: nil)
    }
}
